<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,爬虫," />










<meta name="description" content="python这几天闲的无聊想做一个爬虫来爬取一些‘正经’网站，首先选择用python作为爬虫的语言。但是没有接触过python怎么办呢，只能从头开始学了。python学习地址这个是廖大神写的一个python入门，个人感觉写的非常不错，在粗略的学习了一遍之后感觉可以开始我的爬虫之旅了。">
<meta name="keywords" content="Python,爬虫">
<meta property="og:type" content="article">
<meta property="og:title" content="Python爬虫入门">
<meta property="og:url" content="http://yoursite.com/2016/11/24/python爬虫入门/index.html">
<meta property="og:site_name" content="SISYPHUSER">
<meta property="og:description" content="python这几天闲的无聊想做一个爬虫来爬取一些‘正经’网站，首先选择用python作为爬虫的语言。但是没有接触过python怎么办呢，只能从头开始学了。python学习地址这个是廖大神写的一个python入门，个人感觉写的非常不错，在粗略的学习了一遍之后感觉可以开始我的爬虫之旅了。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/mmhtml.png">
<meta property="og:updated_time" content="2018-03-03T05:15:33.310Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python爬虫入门">
<meta name="twitter:description" content="python这几天闲的无聊想做一个爬虫来爬取一些‘正经’网站，首先选择用python作为爬虫的语言。但是没有接触过python怎么办呢，只能从头开始学了。python学习地址这个是廖大神写的一个python入门，个人感觉写的非常不错，在粗略的学习了一遍之后感觉可以开始我的爬虫之旅了。">
<meta name="twitter:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/mmhtml.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2016/11/24/python爬虫入门/"/>





  <title>Python爬虫入门 | SISYPHUSER</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">SISYPHUSER</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-word">
          <a href="/word/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            word
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2016/11/24/python爬虫入门/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Andy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="SISYPHUSER">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python爬虫入门</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-11-24T15:01:30+08:00">
                2016-11-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="python"><a href="#python" class="headerlink" title="python"></a>python</h3><p>这几天闲的无聊想做一个爬虫来爬取一些‘正经’网站，首先选择用python作为爬虫的语言。但是没有接触过python怎么办呢，只能从头开始学了。<a href="http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" target="_blank" rel="noopener">python学习地址</a>这个是廖大神写的一个python入门，个人感觉写的非常不错，在粗略的学习了一遍之后感觉可以开始我的爬虫之旅了。</p>
<a id="more"></a>
<h3 id="静态网页爬虫"><a href="#静态网页爬虫" class="headerlink" title="静态网页爬虫"></a>静态网页爬虫</h3><p>目标：抓取<a href="http://tieba.baidu.com/p/2166231880中妹子的图片保存在本地" target="_blank" rel="noopener">http://tieba.baidu.com/p/2166231880中妹子的图片保存在本地</a><br>接下来分析一下我们需要做的事</p>
<ul>
<li>获取网页html代码</li>
<li>将html中的图片地址提取出来</li>
<li>根据图片地址获取图片内容</li>
<li>将图片保存在本地</li>
</ul>
<p>话不多少，直接上代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">from urllib import request</span><br><span class="line">from html.parser import HTMLParser</span><br><span class="line">import os</span><br><span class="line"></span><br><span class="line">class MyHtml(HTMLParser):</span><br><span class="line">    path=os.path.join(os.path.abspath(&apos;.&apos;),&apos;pic&apos;)</span><br><span class="line">    if not os.path.exists(path):</span><br><span class="line">        os.mkdir(path)</span><br><span class="line">    def handle_starttag(self,tag,attrs):</span><br><span class="line">        if tag==&apos;img&apos; and attrs[0][0]==&apos;pic_type&apos; and attrs[0][1]==&apos;0&apos;:</span><br><span class="line">            print(attrs[2][1])</span><br><span class="line">            with request.urlopen(attrs[2][1]) as picdate:</span><br><span class="line">                with open(os.path.join(self.path,attrs[2][1][-10:]),&apos;wb&apos;) as fd:</span><br><span class="line">                    fd.write(picdate.read())</span><br><span class="line">with request.urlopen(&apos;http://tieba.baidu.com/p/2166231880&apos;) as f:</span><br><span class="line">    if f.status==200:</span><br><span class="line">        parser=MyHtml()</span><br><span class="line">        parser.feed(f.read().decode(&apos;utf-8&apos;))</span><br><span class="line">    else:</span><br><span class="line">        print (&apos;url error&apos;)</span><br></pre></td></tr></table></figure></p>
<p>这一部分都比较简单，用urllib获取到页面信息后，通过HTMLParser对有用的信息进行提取，然后再使用urllib加载图片保存到本地</p>
<h3 id="获取含有js的复杂网页"><a href="#获取含有js的复杂网页" class="headerlink" title="获取含有js的复杂网页"></a>获取含有js的复杂网页</h3><p>通过上一个例子我们已经对爬虫的爬取过程有了一个初步的了解，接下来我们需要接受更大的世界了。<br>目标:<a href="https://mm.taobao.com/search_tstar_model.htm?spm=719.1001036.1998606017.2.pA4hNo" target="_blank" rel="noopener">https://mm.taobao.com/search_tstar_model.htm?spm=719.1001036.1998606017.2.pA4hNo</a><br>首先想到的是通过之前的经验，先获取html再从html中加载图片信息。<br><img src="http://7xtcmn.com1.z0.glb.clouddn.com/mmhtml.png" alt="html"><br>但是通过查看网页的源码后就发现，原来网页上的那么多的妹子的图片居然一张也没有在源码中显示。看来原来爬取静态网页的方法已经不适用了，我们要使用其他的手段了。</p>
<p>分析出现上述结果是因为网页上的图片项都是通过js添加进去的，那么我们有两种方法来解决这个问题：</p>
<ol>
<li>分析js代码，找出添加的内容</li>
<li>先让js运行，我们从js处理完毕的html中获取我们想要的信息</li>
</ol>
<p>这里我们选择第二种方法，为了让js运行就需要一些工具<br>selenium+PhantomJS<br>selenium是一个自动化测试工具，可以同过 pip install selenium 来安装<br>PhantomJS其实就是一个浏览器，只是它没有界面，我们的js就是依赖它来执行的。<a href="http://phantomjs.org/download.html从这个地址下载，把其中的phantomjs.exe文件放在python目录下（确保你的python目录已经在环境变量中配置好了）" target="_blank" rel="noopener">http://phantomjs.org/download.html从这个地址下载，把其中的phantomjs.exe文件放在python目录下（确保你的python目录已经在环境变量中配置好了）</a></p>
<p>还有一个非常实用的爬虫工具需要安装pip install beautifulsoup4，这个是用来提取html元素的。如果不是很了解可以参考<a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html" target="_blank" rel="noopener">这篇</a>文章<br>好了，准备工作都做好了，可以开工了</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">from urllib import request</span><br><span class="line">from bs4 import BeautifulSoup</span><br><span class="line">from selenium import webdriver</span><br><span class="line">import os</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">class MyHtml():</span><br><span class="line">	def __init__(self):</span><br><span class="line">		self.host=&apos;https://mm.taobao.com/search_tstar_model.htm?spm=719.1001036.1998606017.2.pA4hNo&apos;</span><br><span class="line">		self.path=os.path.join(os.path.abspath(&apos;.&apos;),&apos;mm&apos;)</span><br><span class="line">		if not os.path.exists(self.path):</span><br><span class="line">			os.mkdir(self.path)</span><br><span class="line">		self.browser=webdriver.PhantomJS()</span><br><span class="line">		self.count=0</span><br><span class="line"></span><br><span class="line">	def start(self,n=False):</span><br><span class="line">		if not n:</span><br><span class="line">		    print(self.host)</span><br><span class="line">		    self.browser.get(self.host)</span><br><span class="line">		print(&apos;第&apos;+str(self.count)+&apos;项&apos;)</span><br><span class="line">		self.soup=BeautifulSoup(self.browser.page_source)</span><br><span class="line">		for li in self.soup.find_all(&apos;li&apos;,class_=&apos;item&apos;):</span><br><span class="line">			self.img=li.find(&apos;img&apos;)</span><br><span class="line">			if self.img.has_attr(&apos;data-ks-lazyload&apos;):</span><br><span class="line">				self.src=&apos;https:&apos;+self.img[&apos;data-ks-lazyload&apos;]</span><br><span class="line">			else:</span><br><span class="line">				self.src=&apos;https:&apos;+self.img[&apos;src&apos;]</span><br><span class="line">			print(self.src)</span><br><span class="line">			self.name=str(li.find(&apos;span&apos;,class_=&apos;name&apos;).string)</span><br><span class="line">			try:</span><br><span class="line">				with request.urlopen(self.src) as pic:</span><br><span class="line">					if pic.status==200:</span><br><span class="line">						with open(os.path.join(self.path,self.name+&apos;.jpg&apos;),&apos;wb&apos;) as pici:</span><br><span class="line">							pici.write(pic.read())</span><br><span class="line">			except BaseException:</span><br><span class="line">				print(&apos;这个地址有问题&apos;)</span><br><span class="line">		if self.count&lt;10:#数据太多这里只取前十项</span><br><span class="line">			self.browser.find_element_by_class_name(&apos;page-next&apos;).click()</span><br><span class="line">			# time.sleep(3)</span><br><span class="line">			self.start(True)</span><br><span class="line">		self.count=self.count+1</span><br><span class="line"></span><br><span class="line">if &apos;__main__&apos;==__name__:</span><br><span class="line">	MyHtml().start()</span><br></pre></td></tr></table></figure>
<h3 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h3><p>到这里我们已经知道了python爬虫的入门用法。但是我们发现这个爬虫的效率太低，这时可以用多线程提高爬虫效率。当同一个ip在一个网站访问频率太高时可能会出现验证码，这时需要做访问延迟和使用代理ip。爬虫路还很长，还有许多知识需要学习。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/爬虫/" rel="tag"># 爬虫</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/26/Glide图片加载/" rel="next" title="Glide图片加载">
                <i class="fa fa-chevron-left"></i> Glide图片加载
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/12/23/Mine/" rel="prev" title="简历">
                简历 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="Andy" />
            
              <p class="site-author-name" itemprop="name">Andy</p>
              <p class="site-description motion-element" itemprop="description">Something Wrong</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#python"><span class="nav-number">1.</span> <span class="nav-text">python</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#静态网页爬虫"><span class="nav-number">2.</span> <span class="nav-text">静态网页爬虫</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取含有js的复杂网页"><span class="nav-number">3.</span> <span class="nav-text">获取含有js的复杂网页</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最后"><span class="nav-number">4.</span> <span class="nav-text">最后</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Andy</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
